import { useParams } from 'react-router-dom';
import {
  Form,
  Input,
  Button,
  Select,
  Upload,
  message,
  Row,
  Col,
  Divider,
  Radio,
  DatePicker,
  Cascader,
  Spin,
} from 'antd';
import { useNavigate } from 'react-router-dom';

import { useState, useEffect } from 'react';
import {
  findByDictCode,
  getById,
  findByParentId,
  save,
  updateById,
} from '../../../api';
import moment from 'moment';

const PatientUpdate = (props) => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { Option } = Select;
  const [form] = Form.useForm();

  const [certificatesTypeList, setCertificatesTypeList] = useState([]);
  const [userInfo, setUserInfo] = useState({});
  const [radioValue, setRadioValue] = useState(0);
  const [addressOptions, setAddressOptions] = useState([]);
  const [addressDefaultValue, setAddressDefaultValue] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(async () => {
    setLoading(true);
    const certificatesTypeListData = await findByDictCode('CertificatesType');

    await setCertificatesTypeList(certificatesTypeListData);

    const provinceListData = await findByParentId(86);
    const addressLists = [];
    provinceListData.forEach((_) => {
      addressLists.push({
        value: _.id,
        label: _.name,
        isLeaf: !_.hasChildren,
      });
    });
    setAddressOptions(addressLists);

    if (id) {
      // 修改
      const patientInfoData = await getById(id);
      patientInfoData.birthdate = moment(patientInfoData.birthdate);
      await setUserInfo(patientInfoData);
      form.setFieldsValue({ ...patientInfoData });
      form.setFieldsValue({
        provinceCode: patientInfoData.provinceCode,
        cityCode: patientInfoData.cityCode,
        districtCode: patientInfoData.districtCode,
        addressSelected: [
          patientInfoData.param.provinceString,
          patientInfoData.param.cityString,
          patientInfoData.param.districtString,
        ],
      });
    } else {
      // 添加
      form.setFieldsValue({
        sex: 0,
        isMarry: 0,
        isInsure: 0,
      });
    }

    setLoading(false);
  }, []);

  const onAddressChange = (value, selectedOptions) => {
    console.log(value, selectedOptions);
  };

  const loadAddressData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const provinceListData = await findByParentId(targetOption.value);
    const addressLists = [];
    provinceListData.forEach((_) => {
      addressLists.push({
        value: _.id,
        label: _.name,
        isLeaf: !_.hasChildren,
      });
    });
    targetOption.loading = false;
    targetOption.children = addressLists;
    setAddressOptions([...addressOptions]);
  };

  const onCertificatesTypeChange = (value) => {};

  const changeRadioValue = (e) => {
    setRadioValue(e.target.value);
  };

  const onFinish = async (values) => {
    let result = null;
    if (
      values.addressSelected.length > 0 &&
      typeof values.addressSelected[0] === 'number'
    ) {
      // 使用省市区修改值
      values.provinceCode = values.addressSelected[0];
      values.cityCode = values.addressSelected[1];
      values.districtCode = values.addressSelected[2];
    }
    if (id) {
      values.id = +id;
      result = await updateById(values);
    } else {
      result = await save(values);
    }
    navigate('/user/patient');
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div className='m-l-30 m-r-30'>
      <h2>
        {id ? '修改就诊人' : '添加就诊人'} {loading && <Spin />}
      </h2>
      <Form
        name='basic'
        labelCol={{
          span: 6,
        }}
        wrapperCol={{
          span: 12,
        }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
      >
        <Divider orientation='left' orientationMargin plain>
          就诊人信息
        </Divider>
        <Form.Item
          label='用户姓名'
          name='name'
          rules={[
            {
              required: true,
              message: '请输入真实姓名全称',
            },
          ]}
        >
          <Input placeholder='请输入真实姓名全称' />
        </Form.Item>

        <Form.Item
          name='certificatesType'
          label='证件类型：'
          rules={[
            {
              required: true,
              message: '请选择证件类型',
            },
          ]}
        >
          <Select
            placeholder='请选择证件类型'
            onChange={onCertificatesTypeChange}
            allowClear
          >
            {certificatesTypeList.map((_) => {
              return (
                <Option value={_.value} key={_.id}>
                  {_.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item
          label='证件号码'
          name='certificatesNo'
          rules={[
            {
              required: true,
              message: '请输入联系人证件号码',
            },
          ]}
        >
          <Input placeholder='请输入证件号码' />
        </Form.Item>

        <Form.Item
          name='sex'
          label='用户性别'
          rules={[
            {
              required: true,
              message: '请选择用户性别',
            },
          ]}
        >
          <Radio.Group>
            <Radio value={0}>女</Radio>
            <Radio value={1}>男</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name='birthdate'
          label='出生日期'
          rules={[
            {
              required: true,
              message: '请选择用户出生日期',
            },
          ]}
        >
          <DatePicker />
        </Form.Item>

        <Form.Item
          name='phone'
          label='手机号码'
          rules={[
            {
              required: true,
              message: '请输入正确手机号码',
              validator: (rule, value) => {
                const phoneReg = /^1[3|4|5|7|8][0-9]\d{8}$/;
                if (phoneReg.test(value)) {
                  return Promise.resolve();
                } else {
                  return Promise.reject(new Error('请输入正确手机号码'));
                }
              },
            },
          ]}
        >
          <Input placeholder='请输入手机号码' />
        </Form.Item>

        <Divider orientation='left' orientationMargin plain>
          建档信息（完善后部分医院首次就诊不排队建档）
        </Divider>

        <Form.Item
          name='isMarry'
          label='婚姻状况'
          rules={[
            {
              required: true,
              message: '请选择婚姻状况',
            },
          ]}
        >
          <Radio.Group>
            <Radio value={0}>未婚</Radio>
            <Radio value={1}>已婚</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name='isInsure'
          label='自费/医保'
          rules={[
            {
              required: true,
              message: '请选择自费/医保',
            },
          ]}
        >
          <Radio.Group>
            <Radio value={0}>自费</Radio>
            <Radio value={1}>医保</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name='addressSelected'
          label='当前住址'
          rules={[
            {
              required: true,
              message: '请选择当前住址区域',
            },
          ]}
        >
          <Cascader
            placeholder='请选择当前住址区域'
            options={addressOptions}
            loadData={loadAddressData}
            changeOnSelect
          />
        </Form.Item>

        <Form.Item
          label='详细地址'
          name='address'
          rules={[
            {
              required: true,
              message: '请输入详细地址',
            },
          ]}
        >
          <Input placeholder='应公安机关要求，请填写现真实住址' />
        </Form.Item>

        <Divider orientation='left' orientationMargin plain>
          联系人信息（选填）
        </Divider>

        <Form.Item label='用户姓名' name='contactsName'>
          <Input placeholder='请输入联系人姓名全称' />
        </Form.Item>

        <Form.Item name='contactsCertificatesType' label='证件类型：'>
          <Select
            placeholder='请选择证件类型'
            onChange={onCertificatesTypeChange}
            allowClear
          >
            {certificatesTypeList.map((_) => {
              return (
                <Option value={_.value} key={_.id}>
                  {_.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item label='证件号码' name='contactsCertificatesNo'>
          <Input placeholder='请输入联系人证件号' />
        </Form.Item>

        <Form.Item label='手机号码' name='contactsPhone'>
          <Input placeholder='请输入联系人手机号码' />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 6,
            span: 18,
          }}
        >
          <Button type='primary' htmlType='submit' size='large'>
            <span style={{ color: 'white' }}>提交</span>
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default PatientUpdate;
